﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace _08_UDPClient
{
    class Program
    {

        static void MyServer(IPAddress addr)
        {
            int recv;
            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(addr, 9050);
            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            newsock.Bind(ipep);
            Console.WriteLine("Waiting for a client...");
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)(sender);
            recv = newsock.ReceiveFrom(data, ref Remote);
            Console.WriteLine("Message received from {0}:", Remote.ToString());
            Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
            
        }

        static void Main(string[] args)
        {
            int recv;
            byte[] data = new byte[1024];
            
            if (args.Length > 0)
            {
                // server
                MyServer(IPAddress.Any);
                Console.ReadLine();
                /*
                IPAddress[] addresses =  Dns.GetHostAddresses(Dns.GetHostName());

                foreach (IPAddress adr in addresses)
                {

                    MyServer(adr);
                }*/
            }
            else
            {
                //clint
                IPEndPoint ipep = new IPEndPoint(IPAddress.Loopback, 9050);
                Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                string welcome = "Hello world";
                data = Encoding.ASCII.GetBytes(welcome);
                newsock.SendTo(data, data.Length, SocketFlags.None, ipep);
               
            }

        }
    }
}
